from typing import Any, Dict, List

from common.basic_mongo import get_mongo_collection
from common.basic_redis import build_mg_redis_key, get_redis_conn


async def get_plc_config(*, production_model: str, procedure_code: str) -> List[Dict]:
    demo_conn = get_mongo_collection(collection_name="demo")
    func_result = []
    async for rcd in demo_conn.find(
        {"production_model": production_model, "procedure_code": procedure_code},
        {"_id": 0},
    ):
        func_result.append(
            {
                "production_model": rcd.get("production_model"),
                "procedure_code": rcd.get("procedure_code"),
                "plc_config": rcd.get("plc_config"),
            }
        )
    return func_result


async def upsert_plc_config(
    *,
    production_model: str,
    procedure_code: str,
    plc_config: Dict[str, Any],
    **kwargs,
):
    demo_conn = get_mongo_collection(collection_name="demo")
    await demo_conn.find_one_and_update(
        {
            "production_model": production_model,
            "procedure_code": procedure_code,
        },
        {"$set": {"plc_config": plc_config or {}, **kwargs}},
        upsert=True,
    )


async def redis_test_demo():
    rd_conn = get_redis_conn()
    ts_key = build_mg_redis_key("name")
    await rd_conn.set(ts_key, "hello")
    rs = await rd_conn.get(ts_key)
    print(rs)
